<template>
  <div>
    <el-drawer
      :visible.sync="drawerVisible"
      size="30%"
      :destroy-on-close="true"
      :close-on-click-modal="false"
      :append-to-body="true"
      :with-header="false"
      :wrapper-closable="false"
    >
      <el-container>
        <el-header>
          <div>新增{{ flow.Name }}</div>
        </el-header>
        <el-main class="edit-form main-full-height">
          <el-form
            ref="dataForm"
            :model="instance"
            label-position="right"
            label-width="100px"
          >
            <el-form-item
              label="标题"
              prop="CustomName"
              :rules="[{ required: true, message: '标题必填', trigger: 'blur' }]"
            >
              <el-input
                v-model="instance.CustomName"
                placeholder="请填写流程标题"
              />
            </el-form-item>
            <el-form-item label="流程模板">
              <el-input
                v-model="flow.Name"
                disabled
              />
            </el-form-item>
            <!-- <el-form-item>
            <el-input v-model="flow.Name">
                <template slot="prepend">流程名称：</template>
              </el-input></el-form-item> -->
          </el-form>
          <CreatedForm
            v-if="createdFormData.list && createdFormData.list.length > 0 && drawerVisible"
            ref="createdForm"
            insite="true"
            :data="createdFormData"
            :value.sync="formData"
            :remote="remoteFuncs"
          />
        </el-main>
        <el-footer style="height:auto;min-height:60px">
          <div>
            <el-button
              size="medium"
              @click="onCancel"
            >返回</el-button>
            <el-button
              type="primary"
              size="medium"
              plain
              @click="onSubmit(0)"
            >保存草稿</el-button>
            <el-button
              type="primary"
              size="medium"
              @click="onSubmit(1)"
            >提交</el-button>
          </div>
        </el-footer>
      </el-container>

    </el-drawer>
    <el-dialog
      title="选择审批人"
      :visible.sync="dialogVisible"
      width="500px"
      :destroy-on-close="true"
      :show-close="false"
      :close-on-click-modal="false"
      :append-to-body="true"
    >
      <el-container>
        <el-main class="main-dialog">
          <!-- <el-row>
            <el-col :span="24">
              <div v-for="item in selectUser" :key="item.Id" class="a-list">
                {{ item.Name }}A
              </div>
            </el-col>
          </el-row> -->

          <!-- <el-step>
              <div slot="icon" class="el-icon-arrow-down" />
              <div slot="title">

                <div class="text-normal ">领导审批<span class="margin-left gray light">0 人或签</span>
                </div>
                <div slot="description" class="flex-start ">
                  <div class="text-center">
                    <div class="avater bg-blue" @click="selectApprove">
                      <i class="el-icon-plus text-xxxl padding-top-sm" />
                    </div>

                  </div>

                </div>
              </div>
            </el-step> -->

          <div class=" text-normal ">领导审批<span class="margin-left gray light">2人及以上或签</span> </div>
          <div class="flex-start ">
            <div
              v-for="item in selectUser"
              :key="item.Id"
              class="text-center black light text-normal"
            >
              <div class="avater bg-grey">
                <i class="el-icon-user-solid text-xxxl padding-top-sm white" />
              </div>
              {{ item.Name }}
            </div>

            <div
              class="text-center"
              @click="selectApprove"
            >
              <div class="avater bg-blue">
                <i class="el-icon-plus text-xxxl padding-top-sm" />
              </div>
              请选择
            </div>

          </div>
        </el-main>
        <el-footer>
          <div>
            <!-- <el-button
              size="medium"
              @click="selectApprove"
            >选择审批人</el-button> -->
            <el-button
              size="medium"
              type="primary"
              @click="dialogVisible=false,customVerifiy()"
            >提交</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-dialog>
    <el-dialog
      title="选择人员"
      :visible.sync="approverRoleVisible"
      width="600px"
      append-to-body
      class="promoter_person"
    >
      <el-container>
        <el-main class="flex">
          <div class="person_tree l">
            <ul>
              <li
                v-for="item in userSource"
                :key="item.Id"
                class="check_box not"
                :class="toggleClass(selectUser,item,'Id')&&'active'"
                @click="selectUser=[item]"
              >
                <a :title="item.Name"><img src="@/assets/images/icon_role.png">{{ item.Name }}</a>
              </li>
            </ul>
          </div>
          <div class="has_selected l">
            <p class="clear">已选（{{ selectUser.length }}）
              <a @click="selectUser=[]">清空</a>
            </p>
            <ul>
              <li
                v-for="item in selectUser"
                :key="item.Id"
              >
                <img src="@/assets/images/icon_role.png">
                <span>{{ item.Name }}</span>
                <img
                  src="@/assets/images/cancel.png"
                  @click="removeEle(selectUser,item,'Id')"
                >
              </li>
            </ul>
          </div>
        </el-main>
        <el-footer class="demo-drawer__footer clear">
          <div>
            <el-button @click="approverRoleVisible = false">返回</el-button>
            <el-button
              type="primary"
              @click="approverRoleVisible = false"
            >确定</el-button>
          </div>
        </el-footer>
      </el-container>
    </el-dialog>
    <selectPerson
      ref="selectPersonDialog"
      :echo-list="selectUser"
      @allSelect="chooseUser"
    />
  </div>
</template>
<script>
import selectPerson from '@/views/components/permissions/selectperson'
import CreatedForm from '@/components/flowset/Formcreated/components/CreatedForm'
import { saveFlowInstances, customVerifiy } from '@/api/flow/index'
import store from '@/store'
export default {
  components: {
    CreatedForm,
    selectPerson
  },
  // eslint-disable-next-line vue/require-prop-types
  props: ['flowDesign', 'selectedIds'],
  data() {
    return {
      drawerVisible: false,
      dialogVisible: false,
      approverRoleVisible: false,
      userSource: [],
      selectUser: [],
      selfselection: '',
      DesignType: 0,
      instance: {
        CustomName: '',
        DesignId: '',
        FormData: '',
        InstanceResult: 0,
        Verifier: {}
      },
      instanceId: '',
      flow: {},
      formData: {
        applyuser: {
          Id: store.getters.userdepart.UserId,
          Name: store.getters.userdepart.UserName
        },
        applydepart: {
          Id: store.getters.userdepart.DepartmentId,
          Name: store.getters.userdepart.DepartmentName
        }
      },
      remoteFuncs: {
      }
    }
  },
  computed: {
    createdFormData() {
      var oo = {
        list: [],
        config: { billType: 0 }
      }
      if (this.flow && this.flow.FormContent) {
        oo.list = JSON.parse(this.flow.FormContent)
        oo.list.forEach(item => {
           item.options.disabled = true
        })
        oo.config.billType = this.flow.DesignType
      }
      return oo
    }
  },
  watch: {

  },
  methods: {
    showAddBillDrawer(flowDesign) {
      this.selectUser = []
      this.userSource = []
      this.selfselection = ''
      this.flow = flowDesign
      this.drawerVisible = true
    },
    onCancel() {
      this.resetForm()
    },
    resetForm() {
      this.flow.Name = ''
      this.formData = {
        applyuser: {
          Id: store.getters.userdepart.UserId,
          Name: store.getters.userdepart.UserName
        },
        applydepart: {
          Id: store.getters.userdepart.DepartmentId || store.getters.unitid,
          Name:
            store.getters.userdepart.DepartmentName || store.getters.unitname
        }
      }
      this.drawerVisible = false
      this.$refs['dataForm'].resetFields()
    },
    onSubmit(t) {
      var _this = this
      _this.$refs['dataForm'].validate(valid => {
        if (valid) {
          _this.$refs.createdForm.getData().then(res => {
            var userIds = []
            _this.selectUser.forEach(item => {
              userIds.push(item.Id)
            })
            _this.instance.DesignId = _this.flow.Id
            _this.instance.FormData = JSON.stringify(res)
            _this.instance.InstanceResult = t
            _this.instance.Verifier = userIds
            saveFlowInstances(_this.instance).then(resdata => {
              if (resdata.Msg === 'selfselectionall') {
                _this.selfselection = 'selfselectionall'
                _this.dialogVisible = true
                _this.instanceId = resdata.Extend
              } else if (resdata.Msg === 'selfselection') {
                _this.selfselection = 'selfselection'
                _this.userSource = resdata.Data
                _this.dialogVisible = true
                _this.instanceId = resdata.Extend
              } else {
                _this.$message({
                  message: '流程已提交，请等待审核',
                  type: 'success',
                  duration: 3 * 1000
                })
                _this.resetForm()
                _this.$emit('loaddata')
              }
            })
          })
        }
      })
    },
    customVerifiy() {
      var _this = this
      var userIds = []
      _this.selectUser.forEach(item => {
        userIds.push(item.Id)
      })
      if (userIds.length < 1) {
        _this.$message({
          message: '请选择审批人',
          type: 'error',
          duration: 3 * 1000
        })
      }
      var data = { FlowInstanceId: _this.instanceId, CustomVerifier: userIds }
      customVerifiy(data).then(res => {
        if (res.Msg === 'selfselectionall') {
          _this.selfselection = 'selfselectionall'
          _this.dialogVisible = true
          // _this.instanceId = res.Extend
        } else if (res.Msg === 'selfselection') {
          _this.selfselection = 'selfselection'
          _this.userSource = res.Data
          _this.dialogVisible = true
          // _this.instanceId = res.Extend
        } else {
          _this.$message({
            message: '已提交，请等待审核',
            type: 'success',
            duration: 3 * 1000
          })
          _this.resetForm()
          _this.$emit('loaddata')
        }
      })
    },
    selectApprove() {
      if (this.selfselection === 'selfselectionall') {
        // 选择所有人员
        this.$refs.selectPersonDialog.showSelectPersonDialog()
      } else if (this.selfselection === 'selfselection') {
        this.approverRoleVisible = true
      }
    },
    chooseUser(users) {
      this.selectUser = []
      if (users && users.length > 0) {
        this.selectUser = users
      }
    },
    toggleClass(arr, elem, key = 'id') {
      return arr.some(item => {
        return item[key] === elem[key]
      })
    },
    removeEle(arr, elem, key = 'id') {
      var includesIndex
      arr.map((item, index) => {
        if (item[key] === elem[key]) {
          includesIndex = index
        }
      })
      arr.splice(includesIndex, 1)
    }

  }
}
</script>
<style lang="scss" scoped>
::v-deep.el-table td,
::v-deep.el-table th {
  padding: 0;
  font-size: 12px;
}
::v-deep.el-table .cell {
  line-height: auto;
}
.avater {
  height: 50px;
  width: 50px;
  border-radius: 50%;

  margin: 10px;
  &:hover {
    box-shadow: 2px 2px 5px #ccc;
    cursor: pointer;
  }
}
</style>
